package pers.sloera.leetcode.editor.cn;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 按位与为零的三元组
 *
 * @author sloera
 * @date 2023-03-04 22:38:59
 */
class TriplesWithBitwiseAndEqualToZero {
    public static void main(String[] args) {
        Solution solution = new TriplesWithBitwiseAndEqualToZero().new Solution();
        System.out.println(solution.countTriplets(new int[]{2, 1, 3}));
        System.out.println(solution.countTriplets(new int[]{0, 0, 0}));
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        /**
         * 计算三元组数
         * <p>
         * i,j,k可以重复，因此可以先遍历两个循环，转换成两元组的问题
         */
        public int countTriplets(int[] nums) {
            // 先得到两元与的结果，然后与剩下的一元遍历
            HashMap<Integer, Integer> twiceCountMap = new HashMap<>(nums.length);
            for (int firstNum : nums) {
                for (int secondNum : nums) {
                    twiceCountMap.put(firstNum & secondNum, twiceCountMap.getOrDefault(firstNum & secondNum, 0) + 1);
                }
            }
            return Arrays.stream(nums)
                    .map(num -> twiceCountMap.entrySet().stream().filter(twiceCount -> (twiceCount.getKey() & num) == 0)
                            .mapToInt(Map.Entry::getValue).sum())
                    .sum();
        }
    }
    //leetcode submit region end(Prohibit modification and deletion)

}
